local skynet = require "skynet"
local message_packet = require "common.message_packet"
local proto_manager = require "common.proto_manager"
local msg_center = require "common.msg_center"
local socket = require "skynet.socket"

local client_msg_handlers = {}

function msg_center.setClientMessageHandler(id,handler,enable)
    id = tonumber(id) or 0
    return msg_center.setMessageHandler(client_msg_handlers,id,handler,enable)
end

local function udpCallback(str,form)

    str = str or ""
    local header,err = message_packet.unpack(str,string.len(str))
    if err then
        skynet.error("udpCallback unpack faild! form:" .. tostring(form) .. " err:" .. tostring(err))
        return
    end

    local id = header.id
    msg_center.dispatchMessage(client_msg_handlers,id,form,id,header.data)

end

local raceAddress = skynet.getenv "race_address" or "127.0.0.1"
local racePort = skynet.getenv "race_port" or 9996

local localUdpId = socket.udp(udpCallback,raceAddress,racePort)
if not localUdpId then
    skynet.error("race listen udp failed!")
    skynet.exit()
    return
end
skynet.error("race udp id:" .. tostring(localUdpId))

function msg_center.clearAll()
    msg_center.clearAllDefault()
    client_msg_handlers = {}
end

function msg_center.getListenId()
    return localUdpId
end

function msg_center.getAddress()
    return raceAddress,racePort
end

return msg_center